package games.gong.durid.service.impl;

import games.gong.durid.entity.Permission;
import games.gong.durid.mapper.PermissionMapper;
import games.gong.durid.mapper.RolePermissionMapper;
import games.gong.durid.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    
    @Override
    public int addPermission(Permission permission) {
        // 忽略客户端传递的时间字段，由服务端生成
        permission.setCreateTime(LocalDateTime.now());
        permission.setUpdateTime(LocalDateTime.now());
        int result = permissionMapper.insert(permission);
        return result;
    }
    
    @Override
    public int deletePermission(Long id) {
        // 先删除角色权限关联数据
        rolePermissionMapper.deleteByRoleIdAndPermissionId(null, id);
        // 再删除权限
        int result = permissionMapper.deleteById(id);
        return result;
    }
    
    @Override
    public int updatePermission(Permission permission) {
        // 忽略客户端传递的时间字段，由服务端生成
        permission.setUpdateTime(LocalDateTime.now());
        int result = permissionMapper.update(permission);
        return result;
    }
    
    @Override
    public Permission getPermissionById(Long id) {
        Permission permission = permissionMapper.selectById(id);
        return permission;
    }
    
    @Override
    public List<Permission> getAllPermissions() {
        List<Permission> permissions = permissionMapper.selectAll();
        return permissions;
    }
    
    @Override
    public List<Permission> getPermissionsByRoleId(Long roleId) {
        return permissionMapper.selectPermissionsByRoleId(roleId);
    }
}